package yl.hs.bmipfull.service.production.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yl.hs.bmipfull.daos.laboratory.*;
import yl.hs.bmipfull.daos.production.*;
import yl.hs.bmipfull.daos.salemanage.*;
import yl.hs.bmipfull.daos.system.IDictItemDao;
import yl.hs.bmipfull.daos.vehiclemanage.ITruckInfoDao;
import yl.hs.bmipfull.pojo.laboratory.PackageInfoEntity;
import yl.hs.bmipfull.pojo.laboratory.TaskConfigEntity;
import yl.hs.bmipfull.pojo.production.*;
import yl.hs.bmipfull.pojo.salemanage.*;
import yl.hs.bmipfull.pojo.system.UserInfoEntity;
import yl.hs.bmipfull.pojo.vehiclemanage.TruckInfoEntity;
import yl.hs.bmipfull.service.production.IProductionTaskService;
import yl.hs.bmipfull.service.salemanage.IBuildProjectInfoService;
import yl.hs.bmipfull.service.salemanage.ICustomerInfoService;
import yl.hs.bmipfull.utils.*;
import yl.hs.bmipfull.utils.datastate.ActionType;
import yl.hs.bmipfull.utils.datastate.RelationType;
import yl.hs.bmipfull.viewmodels.PageQuery;
import yl.hs.bmipfull.viewmodels.PageResult;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 作用:  生产任务表服务层接口实现<br/>
 * 创建时间: 2021年05月26日 11时23分11秒 <br/>
 *
 * @author 张凯
 */
@Service
public class ProductionTaskServiceImpl extends ProductionBaseService implements IProductionTaskService {

    @Autowired
    IBuildProjectInfoDao projectInfoDao;
    @Autowired
    IProductionTaskExtandInfoDao productionTaskExtandInfoDao;
    @Autowired
    ITransTaskDao transTaskDao;
    @Autowired
    IProductionTaskDao taskDao;
    @Autowired
    IProductShipOrderDao shipDao;
    @Autowired
    ITaskConfigDao taskConfigDao;
    @Autowired
    IProductCateDao proCateDao;
    @Autowired
    IProductionLineDao lineDao;
    @Autowired
    ISaleOrderDao orderDao;
    @Autowired
    IProductInfoDao proInfoDao;
    @Autowired
    ICustomerInfoService customerSvc;
    @Autowired
    ILinkerInfoDao linkerDao;
    @Autowired
    IBuildProjectInfoService projectSvc;
    @Autowired
    IPackageInfoDao packageInfoDao;
    @Autowired
    ITruckInfoDao truckInfoDao;
    @Autowired
    IDictItemDao dictItemDao;
    @Autowired
    ISaleContractDao contractDao;
    @Autowired
    IContractControlInfoDao contractControlInfoDao;
    @Override
    public PageResult<Map<String, Object>> queryPage(PageQuery pageQuery, int rowNum, int page) throws Exception {
        pageQuery.checkSortSides(ProductionTaskEntity.class);
        pageQuery.getQuery().put("querySkip", (page - 1) * rowNum);
        pageQuery.getQuery().put("pageSize", rowNum);
        PageResult<Map<String, Object>> result = new PageResult(rowNum);

        var cateList = proCateDao.findList(getCompanySNList()).stream().map(t -> t.getSn()).toList();
        pageQuery.getQuery().put("cateArray", cateList);

        var filters = SearchFilterEngine.generateQueryList(pageQuery.getFilters(), ProductionTaskEntity.class);
        result.setRecords(taskDao.queryCountByCondition(pageQuery.getQuery(), filters));
        result.setPage(page);
        var dataList = initTaskDataTag(taskDao.queryPage(pageQuery.getQuery(), filters));
        var filterType = pageQuery.getQuery().get("filter");
        if ("configSet".equals(filterType)) {
            initTaskConfig(dataList);
        }
        result.setData(dataList);
        return result;
    }

    @Override
    public Map<String, Object> getTaskDetailBySN(String sn) {
        ProductionTaskEntity taskEntity = taskDao.findBySN(sn);
        var taskMap = taskEntity.toMap();
        SaleContractEntity saleContract = contractDao.findBySN(taskEntity.getContractSN());
        if (saleContract != null) {
            taskMap.put("contractType", saleContract.getContractType());
        } else {
            taskMap.put("contractType", 0);
        }
        ProductShipOrderEntity orderEntity = shipDao.findListByTaskSNASC(taskEntity.getSn());
        if (orderEntity != null) {
            taskMap.put("outTime", orderEntity.getOutTime());
        } else {
            taskMap.put("outTime", "");
        }
//        double contractOutVol=shipDao.findListByContractSN(taskEntity.getContractSN());
//        List<ContractControlInfoEntity> contractControlInfoList=contractControlInfoDao.queryByContractSn(taskEntity.getContractSN());
        taskMap.put("availableVol", 100);
        return taskMap;
    }

    private List<Map<String, Object>> initTaskConfig(List<Map<String, Object>> dataList) {
        List<Map<String, Object>> newList = new ArrayList<>();

        var configList = taskConfigDao.queryConfigByTaskSNList(dataList.stream().map(t -> t.get("sn").toString()).collect(Collectors.toList()));
        var lineSNList = configList.stream().map(t -> t.getProlineSN()).distinct().collect(Collectors.toList());
        var lineList = lineDao.queryListBySNList(lineSNList);
        for (var item : dataList) {
            var configs = configList.stream().filter(t -> t.getTaskSN().equals(item.get("sn").toString()))
                    .map(t -> t.getProlineSN()).collect(Collectors.toList());

            var findLines = lineList.stream().filter(t -> configs.contains(t.getSn())).map(t -> t.getPlName()).collect(Collectors.toList());
            item.put("configLine", findLines.size() > 0 ? String.join(",", findLines) : "");
            newList.add(item);
        }
        return newList;
    }

    private List<Map<String, Object>> initTaskDataTag(List<ProductionTaskEntity> dataList) {
        var taskSnList = dataList.stream().map(t -> t.getSn()).collect(Collectors.toList());
        var tags = queryAllTagsBySNArray(taskSnList);
        List<Map<String, Object>> newList = new ArrayList<>();
        var packageCode = Tl.getDBMapCode(PackageInfoEntity.class);
        var likerCode = Tl.getDBMapCode(LinkerInfoEntity.class);
        var saleCode = Tl.getDBMapCode(UserInfoEntity.class);
        var customerCode = Tl.getDBMapCode(CustomerInfoEntity.class);
        var orderCode = Tl.getDBMapCode(SaleOrderEntity.class);
        var dataItems = dictItemDao.queryAllItems();
        for (var i = 0; i < dataList.size(); i++) {
            var item = dataList.get(i);
            var task = item.toMap();
            var params =
                    item.getProductionParam().split(";");
            List<String> paramNames = new ArrayList<>();
            if (params.length > 0) {

                for (var param : params) {
                    var paramObj = param.split(":");
                    if (paramObj.length > 1) {
                        if ("productionMode,technicTag,productSlump,imperviousLevel,productBuildWay".indexOf(paramObj[0]) >= 0) {
                            var paramObjStr = paramObj[1].split(",");
                            for (var str : paramObjStr) {
                                var findItem = dataItems.stream().filter(t -> paramObj[0].equals(t.getTypeCode()) && t.getDataValue().equals(str)).findFirst();
                                if (findItem.isPresent()) {
                                    paramNames.add(String.format("[%s]", findItem.get().getDataText()));
                                }
                            }

                        } else if ("technicTag".equals(paramObj[0])) {
                            paramNames.add(String.format("[%s]", paramObj[0]));
                        }
                    }
                }
            }
            task.put("paramName", paramNames.size() > 0 ? String.join(",", paramNames) : "");
            var saleSN = tags.stream().filter(t ->
                    t.getRelationType().equals(RelationType.OWNER.toString())
                            && t.getDataSN().equals(item.getSn())
                            && t.getTagType().equals(saleCode)
            ).map(t -> t.getTagSN()).findFirst();

            var packageSN = tags.stream().filter(t ->
                    t.getRelationType().equals(RelationType.USING.toString())
                            && t.getDataSN().equals(item.getSn())
                            && t.getTagType().equals(packageCode)
            ).map(t -> t.getTagSN()).findFirst();
            var customerSN = tags.stream().filter(t ->
                    t.getRelationType().equals(RelationType.OWNER.toString())
                            && t.getDataSN().equals(item.getSn())
                            && t.getTagType().equals(customerCode)
            ).map(t -> t.getTagSN()).findFirst();
            var orderSN = tags.stream().filter(t ->
                    t.getTagType().equals(orderCode)
                            && t.getRelationType().equals(RelationType.OWNER.toString())
                            && t.getDataSN().equals(item.getSn())
            ).map(t -> t.getTagSN()).findFirst();
            task.put("salerSN", saleSN.isPresent() ? saleSN.get() : "");
            task.put("packageWaySN", packageSN.isPresent() ? packageSN.get() : "");
            task.put("customerSN", customerSN.isPresent() ? customerSN.get() : "");
            task.put("orderSN", orderSN.isPresent() ? orderSN.get() : "");
            newList.add(task);
        }
        return newList;
    }

    @Override
    public ProductionTaskEntity findBySn(String sn) {
        return taskDao.findBySN(sn);
    }

    @Override
    public Map<String, Object> findBySnToMap(String sn) {
        var entity = taskDao.findBySN(sn);
        var map = entity.toMap();
        List<String> list = new ArrayList<>();
        list.add(sn);
        var tags = queryAllTagsBySNArray(list);
        var orderCode = Tl.getDBMapCode(SaleOrderEntity.class);
        if (tags.size() > 0) {
            var orderSN = tags.stream().filter(t ->
                    t.getTagType().equals(orderCode)
                            && t.getRelationType().equals(RelationType.OWNER.toString())
                            && t.getDataSN().equals(entity.getSn())
            ).map(t -> t.getTagSN()).findFirst();
            map.put("orderSN", orderSN.isPresent() ? orderSN.get() : "");
        }
        return map;
    }

    private CustomerInfoEntity customerCheck(String customerName, String sn) throws Exception {
        var customer = customerSvc.findByName(customerName, sn);
        if (customer == null) {
            customer = new CustomerInfoEntity(customerName);
            customerSvc.createCustomer(customer);
        }
        return customer;
    }

    private String projectCheck(String projectName, String address, String customerSN, String customerName) throws Exception {
        var project = projectSvc.findByName(projectName);
        if (project == null) {
            project = new BuildProjectInfoEntity(projectName, address, customerSN, customerName);
            projectSvc.createProject(project);
        }
        return project.getSn();
    }

    @Override
    @Transactional
    public Integer saveProductionTask(Map<String, Object> model, List<ProductionTaskExtendInfoEntity> extandInfoList, String sn) throws Exception {
        Integer result;
        ProductionTaskEntity entity;
        if (Tl.isEmpty(sn)) {
            //执行保存
            entity = new ProductionTaskEntity();
            Tl.getChangeLog(entity, model);
            entity.setSn(queryNewSN(ProductionTaskEntity.class));
            entity = replenishInfo(entity, model);
            entity.setOrganizationCode(getDepartSN());
            entity.setPYFieldValue();
            result = taskDao.insertNew(entity);
            if (result > 0) {
                if (extandInfoList != null) {
                    insertProductionTaskExtandInfo(extandInfoList, entity.getSn());
                }
                sendSysFeatherMessage("编号为" + entity.getSn() + "的生产任务已创建,请及时设置配比信息", "/test/BasicRatioMortar", "配比绑定提醒");
                writeLog(ActionType.CREATE, entity.getSn(), "插入生产任务表信息", Tl.toJson(entity), ProductionTaskEntity.class);
                createLinkerInfo(entity);
            }

        } else {
            //执行修改
            entity = findBySn(sn);
            var backJson = entity.toJson();
            var changeLog = Tl.getChangeLog(entity, model);
            entity = replenishInfo(entity, model);
            entity.setPYFieldValue();
            entity.setOrganizationCode(getDepartSN());
            result = taskDao.update(entity);
            if (result > 0) {
                if (extandInfoList != null) {
                    insertProductionTaskExtandInfo(extandInfoList, entity.getSn());
                }
                saveGS(
                        entity.getSn(),
                        entity.getProjectName(),
                        String.join(",",
                                entity.getCustomName(),
                                entity.getSalerPhone(),
                                entity.getProductName(),
                                entity.getProductSpec(),
                                entity.getSalerName(),
                                entity.getProductCateName(),
                                entity.getProjectLinker(),
                                entity.getProjectName(),
                                entity.getProjectAddr(),
                                entity.getProjectPhone(),
                                entity.getSalerPhone(),
                                entity.getPosition(),
                                entity.getContractSN(),
                                entity.getPackageWay(),
                                entity.getRemark()
                        ),
                        entity,
                        HsApp.getCurrent() != null ? HsApp.getCurrent().getUserSN() : null,
                        null
                );
                createLinkerInfo(entity);
                writeLog(ActionType.UPDATE, sn, changeLog, backJson, ProductionTaskEntity.class);
            }
        }

        if (result > 0) {
            saveGS(
                    entity.getSn(),
                    entity.getProjectName(),
                    String.join(",",
                            entity.getProjectName(),
                            entity.getCustomName(),
                            entity.getProjectAddr(),
                            entity.getProjectLinker(),
                            entity.getProjectPhone(),
                            entity.getPosition(),
                            entity.getProductCateName(),
                            entity.getProductName(),
                            entity.getProductSpec(),
                            entity.getProductionParam(),
                            entity.getSalerName(),
                            entity.getSalerPhone(),
                            entity.getRemark()
                    ),
                    entity,
                    HsApp.getCurrent() != null ? HsApp.getCurrent().getUserSN() : null,
                    entity.getOrganizationCode()
            );
        }
        return result;
    }

    private Integer createLinkerInfo(ProductionTaskEntity taskEntity) {
        LinkerInfoEntity linkEntity = new LinkerInfoEntity();
        SaleContractEntity contractEntity = contractDao.findBySN(taskEntity.getContractSN());
        if (contractEntity != null) {
            linkEntity.setCustSn(contractEntity.getCustomerSN());
            linkEntity.setSn(queryNewSN(LinkerInfoEntity.class));
            linkEntity.setCustType((short) 2);
            linkEntity.setFullName(taskEntity.getProjectLinker());
            linkEntity.setMobilePhone(taskEntity.getProjectPhone());
            Integer result = linkerDao.insertNew(linkEntity);
            if (result > 0) {
                var shareCode = writeUserTag(linkEntity.getSn(), linkEntity.getClass(), RelationType.CREATE.toString());
                saveGS(
                        linkEntity.getSn(),
                        linkEntity.getFullName(),
                        String.join(",",
                                linkEntity.getFullName(),
                                linkEntity.getCustomerName(),
                                linkEntity.getBentInfo(),
                                linkEntity.getCompanyName(),
                                linkEntity.getDepartment(),
                                linkEntity.getPosition(),
                                linkEntity.getLinkFrom(),
                                linkEntity.getMobilePhone(),
                                linkEntity.getQq(),
                                linkEntity.getEmail(),
                                linkEntity.getWechat(),
                                linkEntity.getSupplierName()
                        ),
                        linkEntity,
                        HsApp.getCurrent() != null ? HsApp.getCurrent().getUserSN() : null,
                        shareCode
                );
                writeLog(ActionType.CREATE, linkEntity.getSn(), "插入联系人表信息", Tl.toJson(linkEntity), LinkerInfoEntity.class);
            }
            return result;
        }
        return 0;
    }

    private Integer insertProductionTaskExtandInfo(List<ProductionTaskExtendInfoEntity> extandInfoList, String taskSN) {
        Integer result = 0;
        productionTaskExtandInfoDao.deleteByTaskSN(taskSN);
        for (ProductionTaskExtendInfoEntity extandInfoEntity : extandInfoList) {
            productionTaskExtandInfoDao.insertNew(extandInfoEntity);
        }
        return result;
    }

    private ProductionTaskEntity replenishInfo(ProductionTaskEntity entity, Map<String, Object> model) throws Exception {
        CustomerInfoEntity customer = null;
        if (model.get("customerSN") == null || model.get("customerSN").equals("")) {
            customer = customerCheck(entity.getCustomName(), null);
        } else {
            customer = customerSvc.findBySN(model.get("customerSN").toString());
        }
        writeDataTag(entity.getSn(), entity.getClass(), customer.getSn(), customer.getCustName(), customer.getClass(), RelationType.OWNER.toString());
        projectCheck(entity.getProjectName(), entity.getProjectAddr(), customer.getSn(), entity.getCustomName());
        if (model.get("packageWaySN") != null) {
            var packageInfo = packageInfoDao.findBySN(model.get("packageWaySN").toString());
            if (packageInfo != null) {
                entity.setPackageWeight(packageInfo.getPackWeight());
                entity.setPackageWay(packageInfo.getPackName());
                entity.setPackUnit(packageInfo.getPackUnit());
                writeDataTag(entity.getSn(), entity.getClass(), packageInfo.getSn(), packageInfo.getPackName(), packageInfo.getClass(), RelationType.USING.toString());
            }
        }
        if (!Tl.isEmpty(entity.getProductCateSN())) {
            var cate = proCateDao.findBySN(entity.getProductCateSN());
            if (cate != null) {
                entity.setProductCateName(cate.getCateName());
            }
        }
        if (!Tl.isEmpty(entity.getProductSN())) {
            var product = proInfoDao.findBySN(entity.getProductSN());
            if (product != null) {
                entity.setProductName(product.getProductName());
                entity.setProductSpec(product.getProductSpec());
            }
        }
        if (model.get("salerSN") != null) {
            var saler = userDao.findBySN(model.get("salerSN").toString());
            if (saler != null) {
                writeDataTag(entity.getSn(), entity.getClass(), saler.getSn(), saler.getRealname(), saler.getClass(), RelationType.OWNER.toString());
            }
        }
        var user = HsApp.getCurrent();
        if (user != null) {
            writeDataTag(entity.getSn(), entity.getClass(), user.getUserSN(), user.getUserName(), UserInfoEntity.class, RelationType.CREATE.toString());
        }
        if (model.get("projectLinkerSN") != null) {
            var linker = linkerDao.findBySN(model.get("projectLinkerSN").toString());
            if (linker != null) {
                entity.setProjectLinker(linker.getFullName());
                writeDataTag(entity.getSn(), entity.getClass(), linker.getSn(), linker.getFullName(), linker.getClass(), RelationType.USING.toString());
            }
        }
        if (model.get("orderSN") != null) {
            var order = orderDao.findBySN(model.get("orderSN").toString());
            if (order != null) {

                writeDataTag(entity.getSn(), entity.getClass(), order.getSn(), order.getSn(), order.getClass(), RelationType.OWNER.toString());
            }
        }
        return entity;
    }

    @Override
    public Integer delete(String[] sn) {
        var result = taskDao.changeStateBySn(sn, DataState.DELETED.code);
        if (result > 0) {
            writeLog(ActionType.DELETE, sn, ProductionTaskEntity.class);
            //撤销对应的派车信息
            if (sn.length > 0) {
                truckInfoDao.cancelTaskByTaskSN(sn);
            }
            deleteGs(sn);
        }
        return result;
    }

    @Override
    public Integer updateTask(ProductionTaskEntity taskEntity) {
        return taskDao.update(taskEntity);
    }

    @Override
    public List<ProductionTaskEntity> queryTaskSc(String productCateSN) {
        return taskDao.queryTaskSc(productCateSN);
    }

    @Override
    public List<Map<String, Object>> getTaskByState(PageQuery pageQuery, short state) {
        List<Map<String, Object>> map = new ArrayList<>();
        //获取生产中的工地分组信息
        List<ProductionTaskEntity> taskList = taskDao.getTaskByStateGroupProject(pageQuery.getQuery(), state);
        var projectNameList = taskList.stream().map(t -> t.getProjectName()).toList();
        var projectNameTask = taskDao.getTaskByState(pageQuery.getQuery(), state, null);
        if (taskList.size() < 1) {
            return map;
        }
        //List<Map<String, Object>> projectNameTaskMapList=initTaskDataTag(projectNameTask);
        var taskSNList = projectNameTask.stream().map(t -> t.getSn()).toList();
        var shipOrderList = shipDao.findListByTaskSNList(taskSNList);
        var taskConfigList = taskConfigDao.queryConfigByTaskSNList(taskSNList);
        var TaskExtandList = productionTaskExtandInfoDao.getListTaskSNList(taskSNList);
        var productLineList = lineDao.getAll();
        var projectList = projectInfoDao.findByNameList(projectNameList);
        for (ProductionTaskEntity task : taskList) {
            Map<String, Object> sonMap = new HashMap<>();
            sonMap.put("projectName", task.getProjectName());
            sonMap.put("customName", task.getCustomName());
            List<Map<String, Object>> resultMap = new ArrayList<>();
            var twoList = projectNameTask.stream().filter(t -> t.getProjectName().equals(task.getProjectName())).toList();
            var twoListMap = initTaskDataTag(twoList);
            for (var projectNameTaskMap : twoListMap) {
                var Task = projectList.stream().filter(t -> t.getProjectName().equals(task.getProjectName())).toList();
                if (Task.size() > 0) {
                    projectNameTaskMap.put("projectEntity", Task.get(0));
                } else {
                    projectNameTaskMap.put("projectEntity", null);
                }
                var shipEntityList = shipOrderList.stream().filter(t -> t.getTaskSN().equals(projectNameTaskMap.get("sn").toString())).sorted(Comparator.comparing(ProductShipOrderEntity::getOutTime, Comparator.reverseOrder())).toList();
                ProductShipOrderEntity shipEntity = null;
                if (shipEntityList.size() > 0) {
                    shipEntity = shipEntityList.get(0);
                    if (pageQuery.getQuery().get("productCateSN").equals(HsApp.getSystemSet(CK.MortarSnSysCode))) {
                        ProductShipOrderEntity finalShipEntity = shipEntity;
                        var cumulativeQuantity = shipOrderList.stream().filter(t -> t.getTaskSN().equals(finalShipEntity.getTaskSN())).map(ProductShipOrderEntity::getNetWeight).reduce(BigDecimal.ZERO, BigDecimal::add);
                        projectNameTaskMap.put("cumulativeTrucks", shipEntityList.size());
                        projectNameTaskMap.put("cumulativeQuantity", cumulativeQuantity);
                    } else if (pageQuery.getQuery().get("productCateSN").equals(HsApp.getSystemSet(CK.BetonSysCode))) {
                        projectNameTaskMap.put("cumulativeTrucks", shipEntity.getCumulativeTrucks());
                        projectNameTaskMap.put("cumulativeQuantity", shipEntity.getCumulativeQuantity());
                    } else {
                        projectNameTaskMap.put("cumulativeTrucks", shipEntity.getCumulativeTrucks());
                        projectNameTaskMap.put("cumulativeQuantity", shipEntity.getCumulativeQuantity());
                    }
                    //  格式化时间
                    SimpleDateFormat sdf = new SimpleDateFormat();
                    sdf.applyPattern("yyyy-MM-dd HH:mm:ss");
                    // 获取当前时间
                    Date date = new Date();
                    long min = 0;
                    try {
                        //计算任务单下的最后一张单据距离现在多少分钟
                        min = Tl.dateDiff(sdf.format(date), sdf.format(shipEntity.getOutTime()), "yyyy-MM-dd HH:mm:ss");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    projectNameTaskMap.put("intervalTime", min);
                } else {
                    projectNameTaskMap.put("cumulativeTrucks", 0);
                    projectNameTaskMap.put("cumulativeQuantity", 0);
                    projectNameTaskMap.put("intervalTime", 0);
                }
                var taskConfigEntity = taskConfigList.stream().filter(t -> t.getTaskSN().equals(projectNameTaskMap.get("sn").toString())).toList();
                List<ProductionLineEntity> productLine = new ArrayList<>();
                if (taskConfigEntity.size() > 0) {
                    productLine = productLineList.stream().filter(t -> t.getSn().equals(taskConfigEntity.get(0).getProlineSN())).toList();
                }
                if (productLine.size() > 0) {
                    projectNameTaskMap.put("productionLineName", productLine.get(0).getPlName());
                } else {
                    projectNameTaskMap.put("productionLineName", "");
                }
                projectNameTaskMap.put("PumpTruckList", TaskExtandList.stream().filter(t -> t.getProductionTaskSN().equals(projectNameTaskMap.get("sn").toString())).toList());
                List<TruckInfoEntity> truckInfes = truckInfoDao.queryLikeTaskSN(projectNameTaskMap.get("sn").toString());
                List<Map<String, Object>> transTaskMap = new ArrayList<>();
                if (truckInfes != null && truckInfes.size() > 0) {
                    for (TruckInfoEntity truckInfo : truckInfes) {

                        var transTask = transTaskDao.findByTruckSNAndTaskSN(truckInfo.getSn(), projectNameTaskMap.get("sn").toString());
                        if (transTask != null) {
                            var tTask = transTask.toMap();
                            tTask.put("truckState", truckInfo.getState());
                            //添加生产线字段
                            if (transTask.getProductionLineSN() != null && !"".equals(transTask.getProductionLineSN())) {
                                ProductionLineEntity lineEntity = productLineList.stream().filter(t -> t.getSn().equals(transTask.getProductionLineSN())).toList().get(0);
                                if (lineEntity != null) {
                                    tTask.put("productionLineName", lineEntity.getPlName());
                                }
                            } else {
                                tTask.put("productionLineName", "");
                            }
                            //添加需要发货单中的字段
                            if (transTask.getShipOrderSN() != null && !"".equals(transTask.getShipOrderSN())) {
                                var tranShip = shipOrderList.stream().filter(t -> t.getSn().equals(transTask.getShipOrderSN())).toList();
                                if (tranShip != null && tranShip.size() > 0) {
                                    tTask.put("netWeight", tranShip.get(0).getQuantity());
                                    tTask.put("outTime", tranShip.get(0).getOutTime());
                                    tTask.put("appendWeight", tranShip.get(0).getAppendWeight());
                                }
                            } else {
                                tTask.put("netWeight", 0);
                                tTask.put("outTime", "");
                                tTask.put("appendWeight", 0);
                            }
                            transTaskMap.add(tTask);
                        } else {
                            var tTask = truckInfo.toMap();
                            transTaskMap.add(tTask);
                        }
                    }
                }
                projectNameTaskMap.put("transTaskInfo", transTaskMap);
                resultMap.add(projectNameTaskMap);
            }
            //根据工地分组的任务单计算分组的完成方量和计划方量
            double wcFl = 0;
            double jhFl = 0;
            for (Map<String, Object> vol : resultMap) {
                wcFl = wcFl + Double.parseDouble(vol.get("cumulativeQuantity").toString());
                jhFl = jhFl + Double.parseDouble(vol.get("quantity").toString());
            }
            sonMap.put("sonList", resultMap);
            sonMap.put("wcFl", wcFl);
            sonMap.put("jhFl", jhFl);
            sonMap.put("listCount", twoList.size());
            map.add(sonMap);
        }

//        if (taskList.size() > 0) {
//            for (ProductionTaskEntity task : taskList) {
//                Map<String, Object> sonMap = new HashMap<>();
//                sonMap.put("projectName", task.getProjectName());
//
//                //初始化生产任务单信息
//                List<Map<String, Object>> threeMap = initTaskDataTag(taskDao.getTaskByState(pageQuery.getQuery(), state, task.getProjectName()));
//                List<Map<String, Object>> resultMap = new ArrayList<>();
//                //List<ProductionTaskEntity> list = taskDao.getTaskByState(state, task.getProjectName());
//                if (threeMap.size() > 0) {
//                    for (Map<String, Object> entity : threeMap) {
//
//                        //获取任务单下的最后一条发货单
//                        ProductShipOrderEntity shipEntity = shipDao.findListByTaskSN(entity.get("sn").toString());
//                        List<TaskConfigEntity> taskConfigEntity = taskConfigDao.queryConfigByTaskSN(entity.get("sn").toString());
//                        entity.put("projectEntity", projectInfoDao.findByName(task.getProjectName()));
//
//                        if (taskConfigEntity != null && taskConfigEntity.size() > 0) {
//                            ProductionLineEntity lineEntity = lineDao.findBySN(taskConfigEntity.stream().findFirst().get().getSn());
//                            if (lineEntity != null) {
//                                entity.put("productionLineName", lineEntity.getPlName());
//                            } else {
//                                entity.put("productionLineName", "");
//                            }
//                        } else {
//                            entity.put("productionLineName", "");
//                        }
//                        if (shipEntity != null) {
//
//                            if(pageQuery.getQuery().get("productCateSN").equals(HsApp.getSystemSet(CK.MortarSnSysCode))){
//                                entity.put("cumulativeQuantity", shipDao.getSumNetWeightByTask(entity.get("sn").toString()));
//                            }else if(pageQuery.getQuery().get("productCateSN").equals(HsApp.getSystemSet(CK.BetonSysCode))){
//                                entity.put("cumulativeTrucks", shipEntity.getCumulativeTrucks());
//                                entity.put("cumulativeQuantity", shipEntity.getCumulativeQuantity());
//                            }else{
//                                entity.put("cumulativeTrucks", shipEntity.getCumulativeTrucks());
//                                entity.put("cumulativeQuantity", shipEntity.getCumulativeQuantity());
//                            }
//                            //  格式化时间
//                            SimpleDateFormat sdf = new SimpleDateFormat();
//                            sdf.applyPattern("yyyy-MM-dd HH:mm:ss");
//                            // 获取当前时间
//                            Date date = new Date();
//                            long min = 0;
//                            try {
//                                //计算任务单下的最后一张单据距离现在多少分钟
//                                min = Tl.dateDiff(sdf.format(date), sdf.format(shipEntity.getOutTime()), "yyyy-MM-dd HH:mm:ss");
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                            entity.put("intervalTime", min);
//                        } else {
//                            entity.put("cumulativeTrucks", 0);
//                            entity.put("cumulativeQuantity", 0);
//                            entity.put("intervalTime", 0);
//                        }
//                        entity.put("PumpTruckList", productionTaskExtandInfoDao.getListTaskSN(entity.get("sn").toString()));
//                        //查询任务单下的派车信息
//                        List<TruckInfoEntity> truckInfes=truckInfoDao.queryLikeTaskSN(entity.get("sn").toString());
//                        List<Map<String, Object>> transTaskMap = new ArrayList<>();
//                        if (truckInfes != null && truckInfes.size() > 0) {
//                            for (TruckInfoEntity truckInfo: truckInfes) {
//
//                                var transTask=transTaskDao.findByTruckSNAndTaskSN(truckInfo.getSn(),entity.get("sn").toString());
//                                if(transTask!=null){
//                                    var tTask = transTask.toMap();
//                                    tTask.put("truckState", truckInfo.getState());
//                                    //添加生产线字段
//                                    if (transTask.getProductionLineSN() != null && !"".equals(transTask.getProductionLineSN())) {
//                                        ProductionLineEntity lineEntity = lineDao.findBySN(transTask.getProductionLineSN());
//                                        if(lineEntity != null) {
//                                            tTask.put("productionLineName", lineEntity.getPlName());
//                                        }
//                                    } else {
//                                        tTask.put("productionLineName", "");
//                                    }
//                                    //添加需要发货单中的字段
//                                    if (transTask.getShipOrderSN() != null && !"".equals(transTask.getShipOrderSN())) {
//                                        ProductShipOrderEntity tranShip = shipDao.findBySN(transTask.getShipOrderSN());
//                                        tTask.put("netWeight", tranShip.getNetWeight());
//                                        tTask.put("outTime", tranShip.getOutTime());
//                                        tTask.put("appendWeight", tranShip.getAppendWeight());
//                                    } else {
//                                        tTask.put("netWeight", 0);
//                                        tTask.put("outTime", "");
//                                        tTask.put("appendWeight", 0);
//                                    }
//                                    transTaskMap.add(tTask);
//                                }else{
//                                    var tTask = truckInfo.toMap();
//                                    transTaskMap.add(tTask);
//                                }
//                            }
//                        }
//                        entity.put("transTaskInfo", transTaskMap);
//                        resultMap.add(entity);
//                    }
//                    //根据工地分组的任务单计算分组的完成方量和计划方量
//                    double wcFl = 0;
//                    double jhFl = 0;
//                    for (Map<String, Object> vol : resultMap) {
//                        wcFl = wcFl + Double.parseDouble(vol.get("cumulativeQuantity").toString());
//                        jhFl = jhFl + Double.parseDouble(vol.get("quantity").toString());
//                    }
//                    sonMap.put("sonList", resultMap);
//                    sonMap.put("wcFl", wcFl);
//                    sonMap.put("jhFl", jhFl);
//                    sonMap.put("listCount", threeMap.size());
//                    map.add(sonMap);
//                }
//            }
//        }
        return map;
    }

    @Override
    public Integer updateTask(String sn, short state) {
        var data = taskDao.findBySN(sn);
        data.setState(state);
        //writeLog(ActionType.UPDATE, sn, changeLog, backJson, ProductionTaskEntity.class);
        return taskDao.update(data);
    }

    @Override
    public Integer updateTaskWrite(String sn) {
        var data = taskDao.findBySN(sn);
        data.setWriteTask(true);
        return taskDao.update(data);
    }

    @Override
    public List<ProductionTaskEntity> selectByLineSn(ProductionLineEntity line) {
        return taskDao.queryListByLineSn(line.getSn());
    }

    @Override
    public List<ProductionTaskEntity> queryListByCondition(String catesn, String Condition) {
        return taskDao.queryListByCondition(catesn, Condition);
    }

    @Override
    public Integer changeStateBySn(String[] snList, short state) {
        int result = taskDao.changeStateBySn(snList, state);
        if (result > 0) {
            forWriteLog(snList, state);
        }
        return result;
    }

}